#ifndef MODEL_H
#define MODEL_H

#include "stb_image.h"
#include "includes/assimp/Importer.hpp"
#include "includes/assimp/scene.h"
#include "includes/assimp/postprocess.h"

#include "mesh.h"
#include "shader.h"

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;


class Model : protected QOpenGLFunctions_3_3_Compatibility
{
public:
    /* render data*/
    int texEnable;
    QVector3D orgColor;
    int drawType;
    int lampType;
    QVector3D lightPos;
    QVector3D cameraPos;
    QVector3D cameraFront;
    // for animation
    QMatrix4x4 localModel;
    // Mesh function 1
    void setupMesh(unsigned int &VAO, unsigned int &VBO, unsigned int &EBO, vector<Vertex> &vertices, vector<unsigned int> &indices)
    {
        // create buffers/arrays
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);
        glGenBuffers(1, &EBO);

        glBindVertexArray(VAO);
        // load data into vertex buffers
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        // A great thing about structs is that their memory layout is sequential for all its items.
        // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
        // again translates to 3/2 floats which translates to a byte array.
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

        // set the vertex attribute pointers
        // vertex Positions
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
        // vertex normals
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
        // vertex texture coords
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
        // 暂不需要
//        // vertex tangent
//        glEnableVertexAttribArray(3);
//        glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
//        // vertex bitangent
//        glEnableVertexAttribArray(4);
//        glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));

        glBindVertexArray(0);
    }

    // Mesh function 2
    void DrawMesh(Shader &shader, unsigned int &VAO, vector<unsigned int> &indices, vector<Texture> &textures)
    {
        shader.setInt("texType", texEnable);
        shader.setInt("texNum", texEnable);
        if (texEnable == 1) {
            shader.setInt("material.texture_diffuse", 0);
        } else if (texEnable == 2) {
            shader.setInt("material.texture_diffuse", 1);
        } else if (texEnable == 3) {
            shader.setInt("material.texture_diffuse", 2);
        }
        shader.setVec3("orgColor", orgColor);

        if (lampType == 1) { // point light
            shader.setInt("texType", 4);
            shader.setVec3("light.position", lightPos);
            shader.setVec3("viewPos", cameraPos);
            // light properties 光线衰减使可视距离为50单位
            shader.setFloat("light.constant", 1.0f);
            shader.setFloat("light.linear", 0.09f);
            shader.setFloat("light.quadratic", 0.032f);
            QVector3D t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("light.ambient", t);
            t = QVector3D(0.8f, 0.8f, 0.8f);
            shader.setVec3("light.diffuse", t);
            t = QVector3D(1.0f, 1.0f, 1.0f);
            shader.setVec3("light.specular", t);
            // material properties
            // 环境光
            shader.setVec3("material.ambient", orgColor);
            // 漫反射
            shader.setVec3("material.diffuse", orgColor);
            // 镜面光 : 作适当弱化
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("material.specular", t);
            // 瞎眼系数
            shader.setFloat("material.shininess", 32.0f);
        } else if (lampType == 2) { // directional light
            shader.setInt("texType", 5);
            QVector3D t = QVector3D(-0.2f, -1.0f, -0.3f);
            shader.setVec3("light.direction", t);
            shader.setVec3("viewPos", cameraPos);
            // light properties 平行光不衰减
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("light.ambient", t);
            t = QVector3D(0.8f, 0.8f, 0.8f);
            shader.setVec3("light.diffuse", t);
            t = QVector3D(1.0f, 1.0f, 1.0f);
            shader.setVec3("light.specular", t);
            // material properties
            // 环境光
            shader.setVec3("material.ambient", orgColor);
            // 漫反射
            shader.setVec3("material.diffuse", orgColor);
            // 镜面光 : 作适当弱化
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("material.specular", t);
            // 瞎眼系数
            shader.setFloat("material.shininess", 32.0f);
        }else if (lampType == 3) { // spot light
            shader.setInt("texType", 6);
            shader.setVec3("light.position", cameraPos);
            shader.setVec3("viewPos", cameraPos);
            // light properties 模拟手电筒
            shader.setVec3("light.direction", cameraFront);
            shader.setFloat("light.cutOff", cos(qDegreesToRadians(12.5f)));
            shader.setFloat("light.outerCutOff", cos(qDegreesToRadians(20.5f)));
            // light properties 光线衰减使可视距离为50单位
            shader.setFloat("light.constant", 1.0f);
            shader.setFloat("light.linear", 0.09f);
            shader.setFloat("light.quadratic", 0.032f);
            QVector3D t = QVector3D(0.1f, 0.1f, 0.1f);
            shader.setVec3("light.ambient", t);
            t = QVector3D(0.8f, 0.8f, 0.8f);
            shader.setVec3("light.diffuse", t);
            t = QVector3D(1.0f, 1.0f, 1.0f);
            shader.setVec3("light.specular", t);
            // material properties
            // 环境光
            shader.setVec3("material.ambient", orgColor);
            // 漫反射
            shader.setVec3("material.diffuse", orgColor);
            // 镜面光 : 作适当弱化
            t = QVector3D(0.5f, 0.5f, 0.5f);
            shader.setVec3("material.specular", t);
            // 瞎眼系数
            shader.setFloat("material.shininess", 32.0f);
        }

        // bind appropriate textures
//        unsigned int diffuseNr  = 1;
//        unsigned int specularNr = 1;
//        unsigned int normalNr   = 1;
//        unsigned int heightNr   = 1;
        for(unsigned int i = 0; i < textures.size(); i++)
        {
            glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
            // retrieve texture number (the N in diffuse_textureN)
//            stringstream ss;
//            string number;
            string name = textures[i].type;
//            if(name == "texture_diffuse")
//                ss << diffuseNr++; // transfer unsigned int to stream
//            else if(name == "texture_specular")
//                ss << specularNr++; // transfer unsigned int to stream
//            else if(name == "texture_normal")
//                ss << normalNr++; // transfer unsigned int to stream
//             else if(name == "texture_height")
//                ss << heightNr++; // transfer unsigned int to stream
//            number = ss.str();
//            // now set the sampler to the correct texture unit
//            glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
            glUniform1i(glGetUniformLocation(shader.ID, name.c_str()), i);
            // and finally bind the texture
            glBindTexture(GL_TEXTURE_2D, textures[i].id);
        }

        // draw mesh
        glBindVertexArray(VAO);
        // GL_POINT 点模式
        // GL_LINE 线框模式
        // GL_FILL 面模式
        if (drawType == 1) {
            shader.setInt("texType", 0);
            glEnable(GL_POINT_SMOOTH);
            glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST/*GL_NICEST*/); // 抗锯齿
            glPolygonMode(GL_FRONT, GL_POINT);
            glPolygonMode(GL_BACK, GL_POINT);
        } else if (drawType == 2) {
            shader.setInt("texType", 0);
//            glEnable(GL_LINE_SMOOTH);
//            glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST/*GL_NICEST*/); // 抗锯齿
            glPolygonMode(GL_FRONT, GL_LINE);
            glPolygonMode(GL_BACK, GL_LINE);
        } else if (drawType == 3) {
            glPolygonMode(GL_FRONT, GL_FILL);
            glPolygonMode(GL_BACK, GL_FILL);
        }
        glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
        //glDrawElements(GL_POLYGON, indices.size(), GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // always good practice to set everything back to defaults once configured.
        glActiveTexture(GL_TEXTURE0);
    }

    /*  Model Data */
    vector<Texture> textures_loaded;	// stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once.
    vector<Mesh> meshes;
    string directory;
    bool gammaCorrection;

    /*  Functions   */
    // constructor, expects a filepath to a 3D model.
    Model(string const &path, bool gamma = false) : gammaCorrection(gamma)
    {
        initializeOpenGLFunctions();

        loadModel(path);
    }

    // draws the model, and thus all its meshes
    void Draw(Shader &shader)
    {
        for(unsigned int i = 0; i < meshes.size(); i++) {
            if (i == 1) {
                //localModel.translate(QVector3D(0.0f, 10.0f, 0.0f));
                //localModel.rotate(20.0f, QVector3D(-100.0f, 0.0f, 0.0f));
                shader.setMat4("model", localModel);
            }
            DrawMesh(shader, meshes[i].VAO, meshes[i].indices, meshes[i].textures);
        }
    }

private:
    /*  Functions   */
    // loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
    void loadModel(string const &path)
    {
        // read file via ASSIMP
        Assimp::Importer importer;
        const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate/* | aiProcess_FlipUVs | aiProcess_CalcTangentSpace*//* | aiProcess_SplitLargeMeshes*//* | aiProcess_GenNormals*/);
        // check for errors
        if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
        {
            cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
            return;
        }
        // retrieve the directory path of the filepath
        directory = path.substr(0, path.find_last_of('/')); // teapot.obj

        // process ASSIMP's root node recursively
        processNode(scene->mRootNode, scene);
    }

    // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
    void processNode(aiNode *node, const aiScene *scene)
    {
        // process each mesh located at the current node
        //qDebug() << node->mNumMeshes << node->mNumChildren;
        for(unsigned int i = 0; i < node->mNumMeshes; i++)
        {
            // the node object only contains indices to index the actual objects in the scene.
            // the scene contains all the data, node is just to keep stuff organized (like relations between nodes).
            aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
            meshes.push_back(processMesh(mesh, scene));
        }
        // after we've processed all of the meshes (if any) we then recursively process each of the children nodes
        for(unsigned int i = 0; i < node->mNumChildren; i++)
        {
            processNode(node->mChildren[i], scene);
        }

    }

    Mesh processMesh(aiMesh *mesh, const aiScene *scene)
    {
        Q_UNUSED(scene);
        // data to fill
        vector<Vertex> vertices;
        vector<unsigned int> indices, indices2;
        vector<Texture> textures;

        // load texture by hand
        // texture1
        Texture texture;
        texture.id = TextureFromFile("wall3.bmp", this->directory);
        texture.type = "texture1";
        textures.push_back(texture);
        textures_loaded.push_back(texture);
        // texture2
        texture.id = TextureFromFile("wall4.bmp", this->directory);
        texture.type = "texture2";
        textures.push_back(texture);
        textures_loaded.push_back(texture);
        // texture3
        texture.id = TextureFromFile("wall5.bmp", this->directory);
        texture.type = "texture3";
        textures.push_back(texture);
        textures_loaded.push_back(texture);

        // Walk through each of the mesh's vertices
        //qDebug() << mesh->mNumVertices;
        for(unsigned int i = 0; i < mesh->mNumVertices; i++)
        {
            Vertex vertex;
            QVector3D vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
            vector.setX(mesh->mVertices[i].x);
            vector.setY(mesh->mVertices[i].y);
            vector.setZ(mesh->mVertices[i].z);
            vertex.Position = vector;
            // normals
            if (mesh->mNormals != NULL) { // 添加判断是否有顶点法向量
                vector.setX(mesh->mNormals[i].x);
                vector.setY(mesh->mNormals[i].y);
                vector.setZ(mesh->mNormals[i].z);
                vertex.Normal = vector;
            }
            // texture coordinates
            if (mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
            {
                //qDebug() << mesh->mTextureCoords[0][i].x << mesh->mTextureCoords[0][i].y;
                QVector2D vec;
                // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't
                // use models where a vertex can have multiple texture coordinates so we always take the first set (0).
                vec.setX(mesh->mTextureCoords[0][i].x);
                vec.setY(mesh->mTextureCoords[0][i].y);
                vertex.TexCoords = vec;
            }
            else
                vertex.TexCoords = QVector2D(0.0f, 0.0f);
            // 暂不需要
//            // tangent
//            vector.setX(mesh->mTangents[i].x);
//            vector.setY(mesh->mTangents[i].y);
//            vector.setZ(mesh->mTangents[i].z);
//            vertex.Tangent = vector;
//            // bitangent
//            vector.setX(mesh->mBitangents[i].x);
//            vector.setY(mesh->mBitangents[i].y);
//            vector.setZ(mesh->mBitangents[i].z);
//            vertex.Bitangent = vector;

//            //茶壶盖
//            if (vector.y() > 33.8f) {
//                if ((vector.x() + 1.8f) * (vector.x() + 1.8f) + (vector.z() - 0.7f) * (vector.z() - 0.7f) < 350.0f)
//                    continue;
//            }

            vertices.push_back(vertex);
        }
        // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
        for(unsigned int i = 0; i < mesh->mNumFaces; i++)
        {
            aiFace face = mesh->mFaces[i];
            // retrieve all indices of the face and store them in the indices vector
            for(unsigned int j = 0; j < face.mNumIndices; j++) {
                //qDebug() << indices.size() << face.mIndices[j]; // 2976
                if (indices.size() > 2255) { // 2255
                    indices2.push_back(face.mIndices[j]);
                    continue;
                }
                indices.push_back(face.mIndices[j]);
            }
        }
        // 没有mtl文件 故暂不需要
//        // process materials
//        aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
//        // we assume a convention for sampler names in the shaders. Each diffuse texture should be named
//        // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
//        // Same applies to other texture as the following list summarizes:
//        // diffuse: texture_diffuseN
//        // specular: texture_specularN
//        // normal: texture_normalN

//        // 1. diffuse maps
//        vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
//        textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
//        // 2. specular maps
//        vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
//        textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
//        // 3. normal maps
//        std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
//        textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
//        // 4. height maps
//        std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
//        textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());

        // 茶壶盖
        Mesh ttMesh = Mesh(vertices, indices, textures);
        setupMesh(ttMesh.VAO, ttMesh.VBO, ttMesh.EBO, ttMesh.vertices, ttMesh.indices);
        meshes.push_back(ttMesh);

        // return a mesh object created from the extracted mesh data
        Mesh tMesh = Mesh(vertices, indices2, textures);
        setupMesh(tMesh.VAO, tMesh.VBO, tMesh.EBO, tMesh.vertices, tMesh.indices);
        return tMesh;
    }

    // checks all material textures of a given type and loads the textures if they're not loaded yet.
    // the required info is returned as a Texture struct.
    vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
    {
        //initializeOpenGLFunctions();

        vector<Texture> textures;
        for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
        {
            aiString str;
            mat->GetTexture(type, i, &str);
            // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
            bool skip = false;
            for(unsigned int j = 0; j < textures_loaded.size(); j++)
            {
                if(std::strcmp(textures_loaded[j].path.C_Str(), str.C_Str()) == 0)
                {
                    textures.push_back(textures_loaded[j]);
                    skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
                    break;
                }
            }
            if(!skip)
            {   // if texture hasn't been loaded already, load it
                Texture texture;
                texture.id = TextureFromFile(str.C_Str(), this->directory);
                texture.type = typeName;
                texture.path = str;
                textures.push_back(texture);
                textures_loaded.push_back(texture);  // store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
            }
        }
        return textures;
    }

    unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false) {
        Q_UNUSED(directory);
        Q_UNUSED(gamma);

        string filename = string(path);
        //filename = directory + '/' + filename;

        unsigned int textureID;
        glGenTextures(1, &textureID);

        int width, height, nrComponents;
        unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
        if (data)
        {
            GLenum format;
            if (nrComponents == 1)
                format = GL_RED;
            else if (nrComponents == 3)
                format = GL_RGB;
            else if (nrComponents == 4)
                format = GL_RGBA;

            glBindTexture(GL_TEXTURE_2D, textureID);
            glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
            glGenerateMipmap(GL_TEXTURE_2D);

            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            stbi_image_free(data);
        }
        else
        {
            std::cout << "Texture failed to load at path: " << path << std::endl;
            stbi_image_free(data);
        }

        return textureID;
    }

};

#endif // MODEL_H
